package com.etong.citymap.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.etong.citymap.activity.enumb.StateTwo;
import com.etong.citymap.bean.ScreenBean;
import com.etong.citymap.bean.ToDayBean;
import com.etong.citymap.bean.ViewHolder;
import com.etong.citymap.connect.HttpSendData;
import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.util.ActivityUtil;
import com.etong.citymap.util.DateUtil;
import com.etong.citymap.util.log.LogUtil;

/**
 * 今日提示，历史提示
 */
public class ToDayCueActivity extends Activity implements OnClickListener,
		OnItemClickListener, OnScrollListener {
	ListView listView;
	ListView listView_heshi;
	AlertDialog load;
	LinearLayout mytype_t1;
	LinearLayout mytype_t2;
	LinearLayout my_back;
	LinearLayout mu_refresh;
	private int pageindex = 0;
	private int pageindexlis = 0;
	private int recordCount;
	private int recordCountlis;
	private int getLastVisiblePosition;
	private int lastVisiblePositionY;
	private String creendate; // 所要获取的时间 传入1900-1-1取全部 其他日期取日期当天（格式yyyy-mm-dd）
	private static ArrayList<ToDayBean> ToDayBeans;
	private static ArrayList<ToDayBean> ToDayLisiBeans;
	private StateTwo stateTwo;
	private ScreenBean screenBean;
	private CityApplication cityApplication;
	Handler handler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == 2) {
				load.dismiss();
				String result = msg.getData().getString("result");
				if (result.equals("-3")) {
				} else if (result.equals("-1")) {
					Toast.makeText(ToDayCueActivity.this, "操作错误",
							Toast.LENGTH_SHORT).show();
				} else if (result.equals("-2")) {
					Toast.makeText(ToDayCueActivity.this, "无任务",
							Toast.LENGTH_SHORT).show();
				}
			} else if (msg.what == 3) {
				load.dismiss();
				listView.setAdapter(baseAdapter);
				listView_heshi.setAdapter(baseAdapter1);
			}
			return false;
		}
	});

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cue);
		cityApplication = (CityApplication)getApplication();
		ToDayBeans = new ArrayList<ToDayBean>();
		ToDayLisiBeans = new ArrayList<ToDayBean>();
		screenBean = ActivityUtil.getScreenWidthAndHeight(this);
		load = new ProgressDialog(this);
		load.setTitle(null);
		load.setMessage("请稍等,正在加载数据...");
		load.setCanceledOnTouchOutside(false);
		creendate = DateUtil.setSimpleDateFormat(new Date(), "yyyy-MM-dd");
		stateTwo = StateTwo.Lift;
		init();
	}

	void init() {
		listView = (ListView) findViewById(R.id.tolist);
		listView_heshi = (ListView) findViewById(R.id.tolslist);
		mytype_t1 = (LinearLayout) findViewById(R.id.totype_t1);
		mytype_t2 = (LinearLayout) findViewById(R.id.totype_t2);
		my_back = (LinearLayout) findViewById(R.id.to_back);
		mu_refresh = (LinearLayout) findViewById(R.id.to_refresh);
		mu_refresh.setOnClickListener(this);
		mytype_t1.setOnClickListener(this);
		mytype_t2.setOnClickListener(this);
		listView.setOnItemClickListener(this);
		listView.setOnScrollListener(this);
		listView_heshi.setOnItemClickListener(this);
		my_back.setOnClickListener(this);
	}

	void loading() {
		load.show();
		new Loading();
	}

	class Loading extends Thread {
		public Loading() {
			start();
		}

		@Override
		public void run() {
			String url = "supervisor/ashx/TipList.ashx"; // 001 001
			Map<String, String> map = new HashMap<String, String>();
			map.put("superid", cityApplication.getUserId());
			map.put("tipdate", creendate);
			map.put("pageindex", pageindex + "");
			map.put("pagecount", cityApplication.PageCount + "");
			try {
				String result = HttpSendData.SendGet(url, map, "utf-8",cityApplication.getHTTPURL());
				if (result.equals("-1") || result.equals("-3")
						|| result.equals("-2")) {
					Message message = new Message();
					message.getData().putString("result", result);
					message.what = 2;
					handler.sendMessage(message);
				} else {
					JSONArray jsonArray = new JSONArray(result);
					for (int i = 0; i < jsonArray.length(); i++) {
						ToDayBean toDayBean = new ToDayBean();
						JSONObject jsonObject = jsonArray.getJSONObject(i);
						toDayBean.setTitle(jsonObject.getString("title"));
						toDayBean.setContent(jsonObject.getString("content"));
						toDayBean.setTipflag(jsonObject.getString("tipflag"));
						toDayBean.setIsread(jsonObject.getString("isread"));
						toDayBean.setTipdate(jsonObject.getString("tipdate"));
						toDayBean.setSuperid(jsonObject.getString("superid"));
						if (stateTwo == StateTwo.Lift) {
							ToDayBeans.add(toDayBean);
							recordCount = jsonObject.getInt("recordCount");
						} else {
							recordCountlis = jsonObject.getInt("recordCount");
							ToDayLisiBeans.add(toDayBean);
						}
					}
					Message message = new Message();
					message.what = 3;
					handler.sendMessage(message);
				}
			} catch (Exception e) {
				LogUtil.e(e);
			}
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

		if (view == listView) {
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
				if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
					View v = (View) view.getChildAt(view.getChildCount() - 1);
					int[] location = new int[2];
					v.getLocationOnScreen(location);
					int y = location[1];
					if (view.getLastVisiblePosition() != getLastVisiblePosition
							&& lastVisiblePositionY != y) {
						getLastVisiblePosition = view.getLastVisiblePosition();
						lastVisiblePositionY = y;
						return;
					} else if (view.getLastVisiblePosition() == getLastVisiblePosition
							&& lastVisiblePositionY == y)// 第二次拖至底部
					{
						if (recordCount > ToDayBeans.size()) {
							pageindex++;
							loading();
						} else {
							Toast.makeText(ToDayCueActivity.this,
									"已经没有可以加载的数据了", Toast.LENGTH_SHORT).show();
						}
					}
				}

				getLastVisiblePosition = 0;
				lastVisiblePositionY = 0;
			}
		} else {

			if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
				View v = (View) view.getChildAt(view.getChildCount() - 1);
				int[] location = new int[2];
				v.getLocationOnScreen(location);
				int y = location[1];
				if (view.getLastVisiblePosition() != getLastVisiblePosition
						&& lastVisiblePositionY != y) {
					getLastVisiblePosition = view.getLastVisiblePosition();
					lastVisiblePositionY = y;
					return;
				} else if (view.getLastVisiblePosition() == getLastVisiblePosition
						&& lastVisiblePositionY == y)// 第二次拖至底部
				{
					if (recordCountlis > ToDayLisiBeans.size()) {
						pageindexlis++;
						loading();
					} else {
						if (view.getLastVisiblePosition() > screenBean
								.getScreenHeight()) {
							Toast.makeText(ToDayCueActivity.this,
									"已经没有可以加载的数据了", Toast.LENGTH_SHORT).show();
						}
					}
				}
			}

			getLastVisiblePosition = 0;
			lastVisiblePositionY = 0;

		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent intent = new Intent(this, ToDayCueDetailedActivity.class);
		if (listView == arg0) {
			intent.putExtra("bean", ToDayBeans.get(arg2));
		}
		if (listView_heshi == arg0) {
			intent.putExtra("bean", ToDayLisiBeans.get(arg2));
		}
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		if (mytype_t1 == v) {
			mytype_t1.setBackgroundResource(R.drawable.mytypeback_down);
			mytype_t2.setBackgroundResource(R.drawable.mytypeback);
			listView.setVisibility(LinearLayout.VISIBLE);
			listView_heshi.setVisibility(LinearLayout.GONE);
			stateTwo = StateTwo.Lift;
			creendate = DateUtil.setSimpleDateFormat(new Date(), "yyyy-MM-dd");
			refreshdata();
		}
		if (mytype_t2 == v) {
			mytype_t2.setBackgroundResource(R.drawable.mytypeback_down);
			mytype_t1.setBackgroundResource(R.drawable.mytypeback);
			listView.setVisibility(LinearLayout.GONE);
			listView_heshi.setVisibility(LinearLayout.VISIBLE);
			stateTwo = StateTwo.Right;
			creendate = "1900-1-1";
			refreshdata();
		}
		if (my_back == v) {
			finish();
		}
		if (mu_refresh == v) {
			refreshdata();
		}
	}

	void refreshdata() {
		if (stateTwo == StateTwo.Lift) {
			pageindex = 0;
			ToDayBeans.clear();
		} else {
			pageindexlis = 0;
			ToDayLisiBeans.clear();
		}

		loading();
	}

	@Override
	protected void onResume() {
		refreshdata();
		super.onResume();
	}

	public BaseAdapter baseAdapter = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {

			ViewHolder vHolder;
			if (convertView == null) {
				convertView = LayoutInflater.from(ToDayCueActivity.this)
						.inflate(R.layout.listitemtis, null);
				TextView title = (TextView) convertView
						.findViewById(R.id.listitem1_title);
				TextView date = (TextView) convertView
						.findViewById(R.id.listitem1_date);
				vHolder = new ViewHolder();
				vHolder.setDate(date);
				vHolder.setTitle(title);
				convertView.setTag(vHolder);
			} else {
				vHolder = (ViewHolder) convertView.getTag();
			}
			if (ToDayBeans != null) {
				ToDayBean notesBean = ToDayBeans.get(position);
				vHolder.getTitle().setText(notesBean.getTitle());
				vHolder.getDate().setText(notesBean.getTipdate());
				if (notesBean.getIsread().equals("0")) {
					vHolder.getTitle().setTextColor(Color.BLUE);
				} else {
					vHolder.getTitle().setTextColor(Color.GRAY);
				}
			}
			return convertView;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public int getCount() {
			return ToDayBeans.size();
		}
	};
	public BaseAdapter baseAdapter1 = new BaseAdapter() {

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {

			ViewHolder vHolder;
			if (convertView == null) {
				convertView = LayoutInflater.from(ToDayCueActivity.this)
						.inflate(R.layout.listitemtis, null);
				TextView title = (TextView) convertView
						.findViewById(R.id.listitem1_title);
				TextView date = (TextView) convertView
						.findViewById(R.id.listitem1_date);
				vHolder = new ViewHolder();
				vHolder.setDate(date);
				vHolder.setTitle(title);
				convertView.setTag(vHolder);
			} else {
				vHolder = (ViewHolder) convertView.getTag();
			}
			if (ToDayLisiBeans != null) {
				ToDayBean notesBean = ToDayLisiBeans.get(position);
				vHolder.getTitle().setText(notesBean.getTitle());
				vHolder.getDate().setText(notesBean.getTipdate());
				// 蓝的未读 黑色或灰色读过的
				if (notesBean.getIsread().equals("0")) {
					vHolder.getTitle().setTextColor(Color.BLUE);
				} else {
					vHolder.getTitle().setTextColor(Color.GRAY);
				}
			}
			return convertView;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public int getCount() {
			return ToDayLisiBeans.size();
		}
	};
}
